package com.kucun.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kucun.bean.Page;
import com.kucun.bean.Users;
import com.kucun.service.Userservice;
import com.kucun.util.NetworkUtil;
import com.tgb.test.LogAfterAdvice;
import com.times.util.DateUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Controller
@RequestMapping("/users")
public class UsersController {
	private static final Logger logger = Logger.getLogger(LogAfterAdvice.class.getName());
	
	public static String userna;
	@Autowired
	private Userservice userservice;
	
	/**
	 * 
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/getallusers.html")
	public String getAllUser(int rows,int page,String cs,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Page page1=new Page();
		page1.setI(rows*(page-1));
		page1.setRows(rows);
		page1.setObj(cs);
		System.out.println(page+","+rows);
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Users> list = userservice.findAll(page1);	
		jsonMap.put("total",userservice.getCount(cs).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	
	@RequestMapping("/queryusers.html")
	public String queryusers(String y,String s,int rows,int page,HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String, Object> jsonMap = new HashMap<String, Object>();//定义map  
		List<Users> list = userservice.query(""+y,""+s,rows*(page-1),rows);	
		jsonMap.put("total",userservice.queryCount(y, s).getTotal());//total键 存放总记录数，必须的  
        jsonMap.put("rows",list);//rows键 存放每页记录 list  
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);//格式化result   一定要是JSONObject  
        PrintWriter pw = response.getWriter();
        pw.write(jsonObject.toString());
		return null;
	}
	/**
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser.html")
	public String toAddUser(HttpServletRequest request){
		
		return "/addUser";
	}
	/**
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/addUser.html")
	public String addUser(Users user,HttpServletRequest request){
		userservice.save(user);
		return "redirect:/user/getAllUser.html";
	}
	
	/**
	 * @param user
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/updateuser.html")
	public void updateUser(Users user,HttpServletRequest request,HttpServletResponse response) throws IOException{
	    PrintWriter out = response.getWriter();
	    if (user.getUserid()!=null) {
	    	if(userservice.update(user)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}else{
			if(userservice.save(user)){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
		}
	  
	}
	/**
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUser.html")
	public String getUser(int id,HttpServletRequest request){
		
		request.setAttribute("user", userservice.findById(id));
		return "/editUser";
	}
	/**
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delet.html")
	public void delUser(String id,HttpServletRequest request,HttpServletResponse response){
		String result = "{\"result\":\"error\"}";
		String string=id;
		if(userservice.delete(string)){
			result = "{\"result\":\"success\"}";
		}
		response.setContentType("application/json");
		try {
			PrintWriter out = response.getWriter();
			out.write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	@RequestMapping("/login.html")
	public String login(Users users,HttpServletRequest request){
		String s="/login";
		try {
			Users user1=userservice.login(users.getLogname());
			if (user1!=null&&users.getPassword().equals(user1.getPassword())&&user1.getIsused().equals("是")) {
				user1.setUsername(user1.getLogname());
				request.getSession(true).setAttribute("user",user1);
				s="/page/index";
				logger.info("日期:["+DateUtils.getStringDate()+"]["+users.getLogname()+"] 登录成功！登录IP:["+NetworkUtil.getIpAddress(request)+"]");
			}else{
				request.setAttribute("msg", "用户名或密码错误！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	@RequestMapping("/exit.html")
	public String clear(HttpServletRequest request){
		request.getSession(true).setAttribute("user",null);
		return "/login";
	}
	@RequestMapping("/updateuserpassword.html")
	public void updateUserPassword(HttpServletRequest request,HttpServletResponse response) throws IOException{
	    PrintWriter out = response.getWriter();
	    String userid=request.getParameter("userid");
	    String password=request.getParameter("qrmm");
	    Users user=new Users();
	    user.setUserid(Integer.valueOf(userid));
	    user.setPassword(password);
	    	if(userservice.updateUserPassword(user)>0){
	  			out.write("ok");
	  		}else{
	  			out.write("error");
	  		}
	}

}
